import React from "react";
import configs from "../../../config/env";
import { getAccessToken } from "@/utils/userAuth";
import styles from "./index.less";
import {
  Upload,
  message,
  Button,
  Modal,
  notification,
  Tooltip,
  Icon,
} from "antd";

const content = (
  <div>
    word：doc、docx <br />
    Excel：xls、xlsx <br />
    PPT： ppt、pptx <br />
    图片：jpg、png、bmp、jepg
    <br />
    其他：pdf
  </div>
);

/**
 * post请求
 * @param {String} url [请求的url地址]
 * @param {String} importFile [发到后台的文件参数名]
 */

export default class UploadFiles extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      insertVisible: false,
    };
  }

  render() {
    const { name, url, downloadUrl, jobId } = this.props;
    const { insertVisible } = this.state;
    const _this = this;
    let props = {
      name: "importFile",
      headers: {
        authorization: `Bearer ${btoa(getAccessToken())}`,
      },
      data: () => {
        return {
          jobId: jobId || undefined,
        };
      },
      action: `${configs[API_ENV].API_SERVER}${url}`,
      async beforeUpload(file) {
        const { name } = file;
        var fileType = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        const isXlsxOrXls =
          fileType === "doc" ||
          fileType === "docx" ||
          fileType === "xls" ||
          fileType === "xlsx" ||
          fileType === "ppt" ||
          fileType === "pptx" ||
          fileType === "jpg" ||
          fileType === "png" ||
          fileType === "bmp" ||
          fileType === "jepg" ||
          fileType === "pdf";
        if (!isXlsxOrXls) {
          message.error("上传文件的格式不正确!");
        }

        return isXlsxOrXls;
        // 上传文件大小验证，暂不限制
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   message.error("Image must smaller than 2MB!");
        // }
        // return isXlsxOrXls && isLt2M;
      },
      onChange(info) {
        if (info.file.status !== "uploading") {
          console.log(info.file, info.fileList);
        }

        if (info.file.status === "done") {
          if (info.file.response.code === "0") {
            const items = info.file.response.data?.items;
            if (Object.keys(items).length > 0) {
              for (const v in items) {
                if (items.hasOwnProperty(v)) {
                  const element = items[v];
                  message.error(
                    `行:${element.row} 错误信息:${element.message}`
                  );
                }
              }
            } else {
              message.success(`${info.file.name} file uploaded successfully`);
              _this.props.refreshTable();
              _this.setState({ insertVisible: false });
            }
          } else {
            notification.error({
              message: `请求错误`,
              description: info.file.response.message,
            });
          }
        } else if (info.file.status === "error") {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
      progress: {
        strokeColor: {
          "0%": "#108ee9",
          "100%": "#87d068",
        },
        strokeWidth: 3,
        format: (percent) => `${parseFloat(percent.toFixed(2))}%`,
      },
    };
    return (
      <section style={{ display: "inline" }} className={this.props.className}>
        <Button
          type="primary"
          icon="plus"
          className="btn"
          style={{ marginRight: "16px" }}
          onClick={() => this.setState({ insertVisible: true })}
        >
          导入{name}
        </Button>
        <Modal
          destroyOnClose
          visible={insertVisible}
          title="导入"
          onCancel={() => this.setState({ insertVisible: false })}
          footer={[
            <Tooltip key="Tips" title={content}>
              <Icon type="question-circle" />
            </Tooltip>,
            <Button
              type="primary"
              key="submit"
              style={{ marginLeft: "20px" }}
              onClick={() => this.setState({ insertVisible: false })}
            >
              确定
            </Button>,
          ]}
        >
          <>
            请选择导入文件
            <div key={Math.random()}>
              <Upload {...props}>
                <div className={styles.upload}>
                  <Button>
                    <Icon type="upload" /> 上传
                  </Button>
                </div>
              </Upload>
            </div>
            <a href={downloadUrl} download>
              模版下载
            </a>
          </>
        </Modal>
      </section>
    );
  }
}
